<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>时间戳转换器</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
        }
        .container {
            background-color: white;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            width: 90%;
            max-width: 500px;
        }
        h1 {
            text-align: center;
            margin-top: 0;
            color: #333;
        }
        .converter-section {
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #eee;
        }
        .converter-section:last-child {
            border-bottom: none;
            margin-bottom: 1rem;
        }
        .input-group {
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
        }
        label {
            width: 120px;
            font-weight: bold;
            color: #555;
        }
        input[type="text"], input[type="datetime-local"] {
            flex: 1;
            padding: 0.5rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            padding: 0.5rem 1rem;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
        }
        button:hover {
            background-color: #0056b3;
        }
        .result {
            margin-top: 0.5rem;
            padding: 0.5rem;
            background-color: #e9ecef;
            border-radius: 4px;
            min-height: 20px;
            font-family: monospace;
        }
        .error {
            color: red;
            font-size: 0.9rem;
            margin-top: 0.5rem;
        }
        .hint {
            font-size: 0.8rem;
            color: #888;
            margin-top: 0.2rem;
        }
    </style>
</head>
<body>

<div class="container">
    <h1>时间戳转换器</h1>

    <!-- 时间戳转日期 -->
    <div class="converter-section">
        <h2>时间戳 → 日期时间</h2>
        <div class="input-group">
            <label for="timestampInput">输入时间戳:</label>
            <input type="text" id="timestampInput" placeholder="例如: 1672531199 或 1672531199000">
            <button id="convertToDateTimeBtn">转换</button>
        </div>
        <div class="hint">支持秒级 (10位) 和毫秒级 (13位) 时间戳</div>
        <div class="result" id="dateTimeResult"></div>
        <div class="error" id="timestampError"></div>
    </div>

    <!-- 日期转时间戳 -->
    <div class="converter-section">
        <h2>日期时间 → 时间戳</h2>
        <div class="input-group">
            <label for="datetimeInput">选择日期时间:</label>
            <input type="datetime-local" id="datetimeInput">
            <button id="convertToTimestampBtn">转换</button>
        </div>
        <div class="hint">请选择日期和时间 (24小时制)</div>
        <div class="result" id="timestampResult"></div>
        <div class="error" id="datetimeError"></div>
    </div>

    <!-- 当前时间 -->
    <div class="converter-section">
        <h2>当前时间信息</h2>
        <button id="getCurrentTimeBtn">获取当前时间</button>
        <div class="result" id="currentTimeResult"></div>
    </div>
</div>

<script>
    // DOM 元素
    const timestampInput = document.getElementById('timestampInput');
    const convertToDateTimeBtn = document.getElementById('convertToDateTimeBtn');
    const dateTimeResult = document.getElementById('dateTimeResult');
    const timestampError = document.getElementById('timestampError');

    const datetimeInput = document.getElementById('datetimeInput');
    const convertToTimestampBtn = document.getElementById('convertToTimestampBtn');
    const timestampResult = document.getElementById('timestampResult');
    const datetimeError = document.getElementById('datetimeError');

    const getCurrentTimeBtn = document.getElementById('getCurrentTimeBtn');
    const currentTimeResult = document.getElementById('currentTimeResult');

    // 时间戳转日期时间
    function convertTimestamp() {
        const input = timestampInput.value.trim();
        timestampError.textContent = '';
        dateTimeResult.textContent = '';

        if (!input) {
            timestampError.textContent = '请输入时间戳';
            return;
        }

        let timestamp = Number(input);
        if (isNaN(timestamp)) {
            timestampError.textContent = '请输入有效数字';
            return;
        }

        // 判断是秒级还是毫秒级
        // 一般认为 1e10 (100亿) 是分界点，小于它的是秒级
        if (Math.abs(timestamp) < 1e10) {
            // 秒级时间戳
            timestamp = timestamp * 1000;
        } else if (Math.abs(timestamp) > 1e13) {
             // 大小超出毫秒级范围太多，可能有问题
             timestampError.textContent = '时间戳数值过大或过小';
             return;
        }
        // else 假定为毫秒级

        const date = new Date(timestamp);

        if (isNaN(date.getTime())) {
            timestampError.textContent = '无法根据此时间戳创建有效日期';
            return;
        }

        // 格式化输出
        const isoString = date.toISOString();
        const localeString = date.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
        const utcString = date.toUTCString();

        dateTimeResult.innerHTML = `
            <strong>ISO 8601:</strong> ${isoString}<br>
            <strong>本地时间 (北京):</strong> ${localeString}<br>
            <strong>UTC 时间:</strong> ${utcString}<br>
            <strong>对应毫秒时间戳:</strong> ${date.getTime()}
        `;
    }

    // 日期时间转时间戳
    function convertDatetime() {
        const input = datetimeInput.value;
        datetimeError.textContent = '';
        timestampResult.textContent = '';

        if (!input) {
            datetimeError.textContent = '请选择日期时间';
            return;
        }

        // HTML datetime-local 返回的是 "YYYY-MM-DDTHH:mm" 格式，基于本地时区
        const date = new Date(input);

        if (isNaN(date.getTime())) {
            datetimeError.textContent = '选择的日期时间无效';
            return;
        }

        const timestampSec = Math.floor(date.getTime() / 1000);
        const timestampMs = date.getTime();

        timestampResult.innerHTML = `
            <strong>秒级时间戳:</strong> ${timestampSec}<br>
            <strong>毫秒级时间戳:</strong> ${timestampMs}
        `;
    }

    // 获取当前时间
    function getCurrentTime() {
        const now = new Date();
        const isoString = now.toISOString();
        const localeString = now.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
        const utcString = now.toUTCString();
        const timestampSec = Math.floor(now.getTime() / 1000);
        const timestampMs = now.getTime();

        currentTimeResult.innerHTML = `
            <strong>ISO 8601:</strong> ${isoString}<br>
            <strong>本地时间 (北京):</strong> ${localeString}<br>
            <strong>UTC 时间:</strong> ${utcString}<br>
            <strong>秒级时间戳:</strong> ${timestampSec}<br>
            <strong>毫秒级时间戳:</strong> ${timestampMs}
        `;
    }

    // 事件监听
    convertToDateTimeBtn.addEventListener('click', convertTimestamp);
    convertToTimestampBtn.addEventListener('click', convertDatetime);
    getCurrentTimeBtn.addEventListener('click', getCurrentTime);

    // 初始化：设置 datetime-local 为当前时间（可选）
    // 注意：toIsoString() 是 UTC 时间，需要转换为本地时间格式
    function setInitialDateTimeLocal() {
        const now = new Date();
        // 转换为本地时间的 YYYY-MM-DDTHH:mm 格式
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0'); // Months are zero-based
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        // HTML datetime-local 通常不包含秒
        datetimeInput.value = `${year}-${month}-${day}T${hours}:${minutes}`;
    }
    setInitialDateTimeLocal();

    // 初始化：获取一次当前时间
    getCurrentTime();

</script>

</body>
</html>
